package com.macrohard.admin.config;

import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.macrohard.admin.config.properties.SecurityProperties;
import com.macrohard.admin.domain.AjaxJson;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * [Sa-Token 权限认证] 全局配置类
 */
@RequiredArgsConstructor
@Configuration
@Slf4j
public class SaTokenConfig implements WebMvcConfigurer {

	private final SecurityProperties securityProperties;


	@Bean
	public StpLogic getStpLogicJwt() {
		return new StpLogicJwtForSimple();
	}

/*	*
	 * 注册 [Sa-Token全局过滤器]
 */
	@Bean
	public SaServletFilter getSaServletFilter() {
		return new SaServletFilter()
						// 指定 [拦截路由]
						.addInclude("/**")
						// 指定 [放行路由]
						.addExclude(securityProperties.getExcludes())
						// 指定[认证函数]: 每次请求执行
						.setAuth(r -> StpUtil.checkLogin())
						// 指定[异常处理函数]：每次[认证函数]发生异常时执行此函数
						.setError(e -> {
							log.error("---------- sa全局异常 ");
							e.printStackTrace();
							return AjaxJson.getError(e.getMessage());
						});        		// 前置函数：在每次认证函数之前执行
	}
}
